<template>
  <div class="search">
    <Alert type="warning" show-icon>请注意：如果API上原来已经绑定了一个策略，则会被本策略覆盖，请慎重选择！</Alert>
    <Form ref="form" :model="formItem" :rules="formItemRules" :label-width="100">
      <FormItem prop="authorities">
        <Transfer
          :data="selectApis"
          :list-style="{width: '45%',height: '480px'}"
          :titles="['选择接口', '已选择接口']"
          :render-format="transferRender"
          :target-keys="formItem.apiIds"
          @on-change="handleTransferChange"
          filterable>
        </Transfer>
      </FormItem>
    </Form>
  </div>
</template>

<script>
export default {
  name: 'RateLimitInfo',
  data () {
    return {
      isAdd: true,
      selectApis: [],
      formItemRules: {},
      formItem: this.getFormItem()
    }
  },
  methods: {
    getFormItem () {
      return {
        policyId: '',
        apiIds: []
      }
    },
    setData (data) {
      this.isAdd = true
      if (data && data.policyId) {
        Object.assign(this.formItem, {
          policyId: data.policyId
        })
        this.isAdd = false
      } else {
        this.handleReset()
      }
      this.handleRateLimitApi(this.formItem.policyId)
    },
    handleReset () {
      this.$refs['form'].resetFields()
      this.formItem = this.getFormItem()
    },
    handleSubmit () {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.$http.post(this.$apis.ipLimit.saveIpLimitApis, {
              policyId: this.formItem.policyId,
              apiIds: this.formItem.apiIds.join(',')
            }, this).then(res => {
              resolve(res)
            }).catch(function (err) {
              reject(err)
            })
          }
        })
      })
    },
    handleRateLimitApi (policyId) {
      if (!policyId) {
        return
      }
      const that = this
      const p1 = this.$http.get(this.$apis.authority.api, {}, this)
      const p2 = this.$http.get(this.$apis.ipLimit.getIpLimitApis, { policyId: policyId }, this)
      Promise.all([p1, p2]).then(function (values) {
        const res1 = values[0]
        const res2 = values[1]
        if (res1.code === 0) {
          res1.data.map(item => {
            item.key = item.apiId
            item.label = `${item.prefix.replace('/**', '')}${item.path} - ${item.apiName}`
          })
          that.selectApis = res1.data
        }
        if (res2.code === 0) {
          const apiIds = []
          res2.data.map(item => {
            if (!apiIds.includes(item.apiId)) {
              apiIds.push(item.apiId)
            }
          })
          that.formItem.apiIds = apiIds
        }
        that.modalVisible = true
      })
    },
    transferRender (item) {
      return `<span  title="${item.label}">${item.label}</span>`
    },
    handleTransferChange (newTargetKeys, direction, moveKeys) {
      if (newTargetKeys.indexOf('1') != -1) {
        this.formItem.apiIds = ['1']
      } else {
        this.formItem.apiIds = newTargetKeys
      }
    }
  },
  created () {

  },
  mounted () {
  }
}
</script>

<style scoped lang="less" rel="stylesheet/less">

</style>
